package com.sq.partner.manager.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.ActirationErrorInfo;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.ActirationCardMinMaxDto;
import com.sq.partner.manager.mybatis.model.ActirationCardReceiveDto;
import com.sq.partner.manager.mybatis.model.ActirationCardResultDto;
import com.sq.partner.manager.mybatis.model.ActivationCardSheet;
import com.sq.partner.manager.mybatis.model.DeptDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.ActirationCardCirculationService;
import com.sq.partner.manager.service.ActirationCardPowerService;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 激活卡流转
 * SQ
 *
 */
@Controller
@RequestMapping(value = "/actirationCardCirculation")
public class ActirationCardCirculationController {

	@Resource
	private ActirationCardCirculationService circulationService;
	@Resource
	private ActirationCardPowerService powerService;
	/**
	 * 激活卡流转返回页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index")
	public String indexLoad() throws Exception {
		return "actirationCard/circulation/index";
	}
	/**
	 * 激活卡下发返回页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/issued")
	public String issued() throws Exception {
		return "actirationCard/circulation/issued";
	}
	/**
	 * 激活卡上交返回页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/receive")
	public String receive() throws Exception {
		return "actirationCard/circulation/receive";
	}
	/**
	 * 激活卡流转(上交，下发)
	 * @param session
	 * @param cardId 卡模板id
	 * @param startNo 下发的激活卡号起号
	 * @param number 下发的数量
	 * @param toDep  下发目的机构
	 * @param flag  操作标志（1：上交；0下发）
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/circulation", method = RequestMethod.POST)
	@ResponseBody
	public Result lowerHair(HttpSession session,String cardId,String startNo,String number,String toDep,String flag) throws Exception {
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		ActirationCardResultDto map=circulationService.circulation(gatewayuser, cardId, startNo, number, toDep, flag);
		if(map.isSuccess()){
			return Result.success(ActirationErrorInfo.CIRCUL_1);
		}else{
			return Result.error(map.getMessage());
		}
		
	}
	/**
	 * 接收操作
	 * @param session
	 * @param nOList接收list
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doreceive", method = RequestMethod.POST)
	@ResponseBody
	public Result doReceive(HttpSession session,String cardId,@RequestParam List<String> nOList) throws Exception {
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//数量校验
		if(nOList.size()>5000){
			return Result.error(ActirationErrorInfo.CIRCUL_12);
		}else{
			ActirationCardResultDto map=circulationService.receiveCard(gatewayuser, cardId, nOList);
			if(map.isSuccess()){
				return Result.success(ActirationErrorInfo.CIRCUL_2);
			}else{
				return Result.error(map.getMessage());
			}
		}
		
	}
	/**
	 * 查询待接收列表
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryreceive", method = RequestMethod.POST)
	@ResponseBody
	public Page<ActirationCardReceiveDto> queryReceive(HttpSession session,Page<ActirationCardReceiveDto> page,String comCode,String circuType,String carDefindId,String carDefindName) throws Exception {
		//初始化分页信息
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(StrUtil.isNotEmpty(comCode)){
			paramMap.put("comCode", comCode);
		}
		if(StrUtil.isNotEmpty(circuType)){
			paramMap.put("circuType", circuType);
		}
		if(StrUtil.isNotEmpty(carDefindId)){
			paramMap.put("carDefindId", carDefindId);
		}
		if(StrUtil.isNotEmpty(carDefindName)){
			paramMap.put("carDefindName", "%"+carDefindName+"%");
		}
		paramMap.put("depNo", gatewayuser.getUserComcode());
		page.setMap(paramMap);
		page=circulationService.queryReceive(page);
		return page;
	}
	/**
	 * 查询接收列表
	 * @param session
	 * @param carDefindId 卡类型id
	 * @param comCode 下发机构
	 * @param circuType 接收类型（上交，下发）
	 * @param startNo 开始卡号（可无，没有则查询全部）
	 * @param number 数量（同开始卡号）
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryreceiveList", method = RequestMethod.POST)
	@ResponseBody
	public Page<String> queryReceiveList(HttpSession session,String carDefindId,String comCode,String circuType,String startNo,String number,Page<String> page) throws Exception {
		//初始化分页信息
		Map<String,Object> map = SqlUtil.buildPageMap(page);
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(StrUtil.isNotEmpty(carDefindId)){
			map.put("carDefindId", carDefindId);
		}
		if(StrUtil.isNotEmpty(comCode)){
			map.put("comCode", comCode);
		}
		if(StrUtil.isNotEmpty(circuType)){
			map.put("circuType", circuType);
		}
		if(StrUtil.isNotEmpty(startNo)){
			map.put("startNo", startNo);
		}
		if(StrUtil.isNotEmpty(number)){
			map.put("number", number);
		}
		//截取机构串，去掉第一个单引号，和最后一个单引号
		map.put("depNo", gatewayuser.getUserComcode());
		page.setMap(map);
		return circulationService.queryReceiveList(page);
	}
	/**
	 * 查询当前机构可流转的卡单汇总
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/query", method = RequestMethod.POST)
	@ResponseBody
	public Page<ActirationCardMinMaxDto> queryList(HttpSession session,Page<ActirationCardMinMaxDto> page,String carDefindId,String name) throws Exception {
		//初始化分页信息
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(StrUtil.isNotEmpty(carDefindId)){
			paramMap.put("cardDefindId", carDefindId);
		}
		if(StrUtil.isNotEmpty(name)){
            paramMap.put("name", "%"+name+"%");
        }
		paramMap.put("depNo", gatewayuser.getUserComcode());
		paramMap.put("status", Constants.ACTIR_CARD_STOCK);
		page.setMap(paramMap);
		page=circulationService.queryAllMinMax(page);
		return page;
	}
	/**
	 *  流转数据查询 
	 *  查询可流转的数据
	 * @param session
	 * @param page
	 * @param cardDefindId 卡模板id
	 * @param startNo 开始卡号
	 * @param number 数量
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querylowerHair", method = RequestMethod.POST)
	@ResponseBody
	public Page<String> querylowerHair(HttpSession session,Page<String> page,String cardDefindId,String startNo,String number) throws Exception {
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//校验字段空
		if(StrUtil.isNotEmpty(cardDefindId)&&StrUtil.isNotEmpty(startNo)&&StrUtil.isNotEmpty(number)){
			//初始化分页信息
			Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
			//放入查询条件
			paramMap.put("cardDefindId", cardDefindId);
			paramMap.put("startNo", startNo);
			paramMap.put("number", number);
			paramMap.put("status", Constants.ACTIR_CARD_STOCK);
			//当前登录机构
			paramMap.put("depNo", gatewayuser.getUserComcode());
			page.setMap(paramMap);
			page=circulationService.queryCardNum( page);
			//校验数量提示信息
			long totle=page.getTotal();
			long num=Long.parseLong(number);
			if(totle<num){
				page.setMessage(ActirationErrorInfo.CIRCUL_3+totle);
			}
			return page;
		}else{
			Page<String> errorPage=new Page<String>();
			errorPage.setResult("error");
			errorPage.setMessage(ActirationErrorInfo.DEFINE_CARD_13);
			return errorPage;
		}
	}
	/**
	 * 查询最大最小号和数量
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/querynumber", method = RequestMethod.POST)
	@ResponseBody
	public ActirationCardMinMaxDto queryMinMax(HttpSession session,String cardDefindId) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(StrUtil.isNotEmpty(cardDefindId)){
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("depNo", gatewayuser.getUserComcode());
			map.put("cardDefindId", cardDefindId);
			return circulationService.queryMinMax(map);
		}else{
			return new ActirationCardMinMaxDto();
		}
	}
	/**
	 * 查询当前机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querycompany", method = RequestMethod.POST)
	@ResponseBody
	public String queryCom(HttpSession session) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		return gatewayuser.getUserComcode();
	}
	/**
	 * 查询当前机构的下级机构（下发用）
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querycompanydown", method = RequestMethod.POST)
	@ResponseBody
	public List<DeptDto> querycomdown(HttpSession session) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		return circulationService.queryComDown(gatewayuser.getUserComcode());
	}
	/**
	 * 查询向上一级上级机构
	 * @param session
	 * @return	
	 * @throws Exception
	 */
	@RequestMapping(value = "/querycompanyup", method = RequestMethod.POST)
	@ResponseBody
	public List<DeptDto> querycomup(HttpSession session) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		return circulationService.queryComUp(gatewayuser.getUserComcode());
	}
	/**
	 * 查询当前机构该卡类型可操作最大张数
	 * @param session
	 * @param startNo 开始卡号
	 * @param flag 操作标识 0：上交下发 1：可接收 （为0时查询可流转的最大张数，为1是查询可接收的最大张数）
	 * @return cardDefineId 卡定义id
	 * @throws Exception
	 */
	@RequestMapping(value = "/querymaxnum", method = RequestMethod.POST)
	@ResponseBody
	public String queryMaxnum(HttpSession session,String cardDefineId,String startNo,String flag) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//添加条件
		HashMap<String,Object> paramMap=new HashMap<String, Object>();
		String num="0";
		if(StrUtil.isNotEmpty(cardDefineId)&&StrUtil.isNotEmpty(startNo)&&StrUtil.isNotEmpty(flag)){
			paramMap.put("cardDefineId", cardDefineId);
			paramMap.put("startNo", startNo);
			paramMap.put("depNo", gatewayuser.getUserComcode());
			if("0".equals(flag)){
				//状态为库存
				paramMap.put("status", Constants.ACTIR_CARD_STOCK);
				num=circulationService.queryMaxnum(paramMap);
			}
			else if("1".equals(flag)){
				//状态为上交，下发
				paramMap.put("status", "'"+Constants.ACTIR_CARD_HAND_UP+"','"+Constants.ACTIR_CARD_HAND_DOWN+"'");
				num=circulationService.queryjsMaxnum(paramMap);
			}
			
			
		}
		return num;
	}
	/**
	 * 总库存查询
	 * 查询当前机构总库存（查询条件，卡模板，卡状态，单证类型）
	 * @param session
	 * @param cardDefineId 卡定义模板ID 
	 * @param status 卡单状态
	 * @param visaType 单证类型
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryStock", method = RequestMethod.POST)
	@ResponseBody
	public Page<ActivationCardSheet> queryStock(HttpSession session,Page<ActivationCardSheet> page,String cardDefineId,String status,String docId,String cardDefineName,String startNo,String endNo) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//初始化分页信息
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		//添加查新条件
		if(StrUtil.isNotEmpty(cardDefineId)){
			paramMap.put("cardDefineId", cardDefineId);
		}
		if(StrUtil.isNotEmpty(status)){
			paramMap.put("status", status);	
		}
		if(StrUtil.isNotEmpty(docId)){
			paramMap.put("docId", docId);
		}
		if(StrUtil.isNotEmpty(cardDefineName)){
			paramMap.put("cardDefineName", "%"+cardDefineName+"%");
		}
		if(StrUtil.isNotEmpty(startNo)){
			paramMap.put("startNo", startNo);
		}
		if(StrUtil.isNotEmpty(endNo)){
			paramMap.put("endNo", endNo);
		}
		//总公司查询所有
		if(!"00".equals(gatewayuser.getUserComcode())){
			paramMap.put("deptno", gatewayuser.getUserComcode());
		}
		page.setMap(paramMap);
		page=circulationService.queryStock(page);
		return page;
	}
	/**
	 * 按照卡号延期
	 * @param session
	 * @param delayList 卡号list
	 * @param date 延长至时间点，新的有效止期
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/cardDelayList", method = RequestMethod.POST)
	@ResponseBody
	public Result cardDelayList(HttpSession session,@RequestParam List<String> delayList,String date) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//权限校验
		if(StrUtil.isNotEmpty(gatewayuser.getUserPower())&&powerService.checkPower(gatewayuser.getUserPower(), Constants.ACTIR_CARD_POWER_DELAY)){
			if(StrUtil.isNotEmpty(date)&&null!=delayList){

				ActirationCardResultDto result=circulationService.cardDelayList(gatewayuser, delayList, date);
				if(result.isSuccess()){
					return Result.success(ActirationErrorInfo.CIRCUL_4);
				}else{
					return Result.error(ActirationErrorInfo.CIRCUL_5+result.getMessage());
				}
			}else{
				return Result.error(ActirationErrorInfo.DEFINE_CARD_13);
			}
		}else{
			return Result.error(ActirationErrorInfo.USER_10);
		}
	}
	/**
	 * 按照起止号批量延期
	 * @param session
	 * @param startNo 开始卡号
	 * @param endNo 终止卡号
	 * @param date 新的有效止期 格式yyyyMMdd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/cardDelay", method = RequestMethod.POST)
	@ResponseBody
	public Result cardDelaybyNoNum(HttpSession session,String startNo,String endNo,String date) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		//权限校验
		if(StrUtil.isNotEmpty(gatewayuser.getUserPower())&&powerService.checkPower(gatewayuser.getUserPower(), Constants.ACTIR_CARD_POWER_DELAY)){
			//字段校验
			if(StrUtil.isNotEmpty(startNo)&&StrUtil.isNotEmpty(endNo)&&StrUtil.isNotEmpty(date)){
				ActirationCardResultDto result=circulationService.cardDelaybyNoNum(gatewayuser, startNo, endNo, date);
				if(result.isSuccess()){
					return Result.success(ActirationErrorInfo.CIRCUL_6);
				}else{
					return Result.error(ActirationErrorInfo.CIRCUL_7+result.getMessage());
				}
			}else{
				return Result.error(ActirationErrorInfo.DEFINE_CARD_13);
			}
		}else{
			return Result.error(ActirationErrorInfo.USER_10);
		}
	}
}
